var fs = require("fs");
var topoObject;

//读入各种文件并调用相应的处理程序
function readFiles(){
    
    //读入拓扑文件并处理
    fs.readFile("./inputFile2.txt", 'utf8',function(err,data) {
        if(err) {
            console.log("err occur when read file");
        }
        else {
            topoObject = dataProcess(data);
            console.log(topoObject);
            writeTopoData(topoObject);
        }
    });
}
//topo文件的处理数据写入
function writeTopoData(topoObject) {
    var jsonText = JSON.stringify(topoObject);
    
    fs.writeFile("./topoOutput.json", jsonText, function(err){
        if(err) {
            console.log("写入文件失败");
        }
    });
   
}

//topo数据处理函数
function dataProcess(data) {
    if(typeof data === 'string') {
        var dataArr = data.split("\n");
        
        var flag = false;
        var topoMsgLine = {}, linkMsgLine = {}, topoMsg = {}, linkMsg = [], result = {};
        
        for(var i = 0; i < dataArr.length - 1; i++) {
            if(dataArr[i] === "") {
                flag = true;
            }
            else if(flag === false) {
                topoMsgLine = dataArr[i].split(" ");
                
                topoMsg[topoMsgLine[0].toLowerCase()] = parseInt(topoMsgLine[1]);
            }
            else {
                linkMsgLine = dataArr[i].split(" ");
                var temp = {};
                temp.s = linkMsgLine[1];
                temp.d = linkMsgLine[2];

                linkMsg.push(temp);
            }
        }
        result.topoInfo = topoMsg;
        result.links = linkMsg;
        return result;
    }
    else {
        console.log("fileData is not string.");
        return "";
    }
}

//调用read函数
readFiles();